package com.anli02.kafkaStream;

import com.alibaba.fastjson.JSON;
import com.anli02.entity.enums.HotArticleConstants;
import com.anli02.entity.pojo.ArticleVisitStreamMess;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class ArticleIncrHandleListener {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @KafkaListener(topics = HotArticleConstants.HOT_ARTICLE_CONSUMER_QUEUE)
    public void handle(String message) {
        ArticleVisitStreamMess mess= JSON.parseObject(message, ArticleVisitStreamMess.class);
        //对分值进行处理
        savemess(mess);

        log.info("收到消息:{}", message);
    }

    private void savemess(ArticleVisitStreamMess mess) {
        //拿出点赞 评论 浏览-id的权重
        //计算总评分-存入redis-id+总积分-叠加//总积分表 -mucisid id->根据音乐id总权拿id
        int score=mess.getLike()*5+mess.getComment()*2+mess.getView();
        redisTemplate.opsForZSet().add(HotArticleConstants.HOT_ARTICLE_REDIS_QUEUE,mess.getMuicid(),score);

        //根据数量-评论 浏览 id 修改es对应的最新数量
        UpdateRequest updateRquest=new UpdateRequest();
        updateRquest.index("online_music_index").id(mess.getMuicid()).doc(mess);


        Map<String, Object> params = new HashMap<>();
        params.put("view", mess.getView());
        params.put("comment", mess.getComment());
        params.put("like", mess.getLike());

        Script script = new Script(ScriptType.INLINE, "painless",
                "ctx._source.comments += params.comment;" +
                        "ctx._source.views += params.view;" +
                        "ctx._source.likes += params.like;",
                params);
        updateRquest.script(script);
        try {
            restHighLevelClient.update(updateRquest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //目前能像到的就这样
    }
}
